<template>
  <div class="login-popup" :class="closingClassName">
    <div class="getAuth" v-if="getAuthStep1">
      <div class="mask" @click="closeHandle"></div>
      <div class="content">
        <div class="close" @click="closeHandle" v-if="showClose">
          <van-icon name="cross" color="#969CA1" size="1em"></van-icon>
        </div>
        <div class="desc" v-if="!isShowProtocol">
          <div class="title">登录查看名片详情</div>
          <div class="text">
            <img src="../static/images/login.png" alt="" />
          </div>
        </div>
        <div class="protocol" v-else>
          <div class="title">用户协议及隐私政策</div>
          <div class="text">
            <Privacy></Privacy>
          </div>
        </div>

        <div class="btn">
          <template v-if="isShowProtocol">
            <div class="checkbox">
              <van-checkbox
                :value="isCheckedProtocol"
                checked-color="#07c160"
                @change="isCheckedProtocol = !isCheckedProtocol"
              >
                我已阅读并同意以上
                <text @click.stop="isShowProtocol = !isShowProtocol"
                  >用户协议及隐私政策</text
                >
              </van-checkbox>
              <div
                class="toggle-protocol"
                v-if="!showProtocol"
                @click="isShowProtocol = !isShowProtocol"
                :class="!isShowProtocol || 'hide'"
              >
                <van-icon name="arrow-up"></van-icon>
              </div>
            </div>
            <van-button
              v-if="isCheckedProtocol"
              size="normal"
              :loading="loading"
              round
              type="primary"
              open-type="getUserInfo"
              @getuserinfo="getUserInfo"
              :lang="'zh_CN'"
              with-credentials
              >微信登录
            </van-button>
            <van-button
              v-else
              round
              type="primary"
              size="normal"
              disabled
              @click="$toast('请确认用户协议及隐私政策')"
            >
              微信登录
            </van-button>
          </template>
          <van-button
            v-else
            round
            block
            type="primary"
            @click.stop="isShowProtocol = !isShowProtocol"
          >
            查看隐私政策并微信授权
          </van-button>
        </div>
      </div>
    </div>
    <div class="getAuth2 login-popup" v-if="getAuthStep2">
      <div class="mask"></div>
      <div class="content">
        <div class="title">请选择你的手机号</div>
        <div class="btn">
          <van-button type="default" @click="postMobile(userInfo.masterMobile)">
            {{ userInfo.masterMobile }}
          </van-button>
        </div>
        <div class="btn" v-if="userInfo.spouseMobile">
          <van-button type="default" @click="postMobile(userInfo.spouseMobile)">
            {{ userInfo.spouseMobile }}
          </van-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { memberAuth, memberAuthStep2, getUpdatePrivacy } from "@/api";
import Privacy from "./Privacy";

export default {
  name: "login-popup",
  components: {
    Privacy
  },
  props: {
    show: {
      type: Boolean,
      default: false
    },
    showProtocol: {
      type: Boolean,
      default: false
    },
    showClose: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      loading: false,
      closingClassName: "",
      isCheckedProtocol: false,
      isShowProtocol: this.showProtocol,
      userInfo: {},
      getAuthStep1: true,
      getAuthStep2: false,
      loginTime: 0
    };
  },
  computed: {
    selectMobile() {
      return !!this.userInfo.spouseMobile;
    }
  },
  methods: {
    postMobile(num) {
      if (!num) {
        this.$store.dispatch("updateUserInfo", this.userInfo);
        this.$emit("login-success");
        this.$toast.success("登录成功");
        return;
      }

      memberAuthStep2({ ...this.userInfo, mobile: num }).then(res => {
        this.$store.dispatch("updateUserInfo", res.data);
        this.userInfo = res.data;
        getUpdatePrivacy(res.data.id).then( r => {
          console.log('rrrrrrrrrrrrrr----')
          console.log(r)
        })
        this.$emit("login-success");
        this.$toast.success("登录成功");
      });
    },
    closeHandle() {
      if (!this.showClose) return;
      this.$emit("login-close");
    },
    getUserInfo(data) {
      this.loading = true;
      // 成功
      if (data.detail.errMsg === "getUserInfo:ok") {
        this.$emit("getUserInfo", data);
        this.wechatLogin(data.detail);
      } else {
        console.log(data.detail.errMsg);
        this.loading = false;
        this.$emit("getUserInfo:failed", data);
      }
    },
    wechatLogin(wxData) {
      const {
        userInfo,
        encryptedData,
        iv,
        cloudID,
        rawData,
        signature
      } = wxData;
      wx.login({
        success: ({ errMsg, code }) => {
          if (code) {
            console.log(code);
            memberAuth({ code, encryptedData, iv, cloudID, rawData, signature })
              .then(data => {
                if (data.code === 200) {
                  if (data.data) {
                    this.userInfo = {
                      ...data.data,
                      headImgUrl: userInfo.avatarUrl,
                      ...userInfo
                    };
                  } else {
                    this.userInfo = {
                      headImgUrl: userInfo.avatarUrl,
                      ...userInfo
                    };
                  }

                  delete this.userInfo.avatarUrl;

                  this.getAuthStep1 = false;
                  if (data.data) {
                    if (!data.data.spouseMobile) {
                      this.postMobile(data.data.masterMobile);
                    } else {
                      this.getAuthStep2 = true;
                    }
                  } else {
                    this.postMobile();
                  }
                } else {
                  this.loading = false;
                  this.$toast.fail(data.message);
                }
              })
              .catch(e => {
                if (this.loginTime < 3) {
                  this.loginTime++;
                  console.log("code 过期重试：", this.loginTime);
                  setTimeout(() => this.wechatLogin(wxData), 500);
                } else {
                  wx.showModal({
                    title: "登录失败",
                    showCancel: false,
                    content: JSON.stringify(e) + "__code:" + code
                  });
                  this.loading = false;
                }
              });
          } else {
            // 重试3次
            if (this.loginTime < 3) {
              this.loginTime++;
              setTimeout(() => this.wechatLogin(userInfo), 500);
            } else {
              wx.showToast({
                title: "登录失败，获取不到code！" + errMsg,
                icon: "none",
                duration: 2000
              });
            }
          }
        }
      });
    }
  }
};
</script>

<style lang="less">
.login-popup {
  position: fixed;
  left: 0;
  top: 0;
  width: 100vw;
  height: 100vh;

  .mask {
    background: rgba(1, 9, 32, 0.4);
    display: block;
    position: absolute;
    left: 0;
    top: 0;
    right: 0;
    bottom: 0;
    animation: fadeIn both 500ms;
  }

  .content {
    animation: fadeInDown both 500ms;
    background-color: #fff;
    border-radius: 24px 24px 0 0;
    position: absolute;
    bottom: 0;
    left: 0;
    width: 100vw;
    padding: 35px;
    box-sizing: border-box;
    overflow: hidden;
    transition: all 500ms;

    .close {
      position: absolute;
      top: 0;
      right: 0;
      padding: 40px 40px;
    }

    .title {
      font-size: 42px;
      font-weight: 800;
      color: rgba(0, 0, 0, 1);
      text-align: center;
      line-height: 1.5;
      margin-bottom: 60px;
      margin-top: 20px;
    }

    .protocol {
      min-height: 320px;

      .title {
        margin-bottom: 46px;
      }

      .text {
        font-size: 28px;
        color: #666;
        max-height: 400px;
        overflow-y: scroll;
        line-height: 1.6;
        padding-left: 20px;
        padding-right: 20px;
      }
    }

    .desc {
      padding: 0 62px 52px 62px;

      img {
        width: 573px;
        height: 150px;
      }
    }

    .btn {
      padding-bottom: 46px;
      text-align: center;

      .van-button--normal {
        padding: 0 2.6em;
        height: 96px;
        line-height: 96px;
        font-size: 36px;
        border-radius: 60px;
        width: 80%;
        margin: 0 auto;
      }

      .checkbox {
        border-top: 1px solid rgba(217, 217, 217, 1);
        margin-top: 20px;
        padding-top: 40px;
        text-align: left;
        font-size: 30px;
        color: #000;
        margin-bottom: 42px;
        position: relative;

        .van-checkbox__label {
          margin-left: 10px;
        }

        text {
          color: #576b95;
        }

        .toggle-protocol {
          width: 48px;
          height: 48px;
          color: #000;
          border-radius: 50%;
          overflow: hidden;
          border: 1px solid #c8c8cd;
          position: absolute;
          right: 0;
          bottom: -3px;
          box-sizing: border-box;
          padding: 0.16em 0.25em;
          transition: all 500ms;

          &.hide {
            transform: rotate(180deg);
          }
        }
      }
    }
  }
}

@keyframes fadeInDown {
  from {
    transform: translateY(100%);
    opacity: 0;
  }
  to {
    transform: none;
    opacity: 1;
  }
}
</style>
